
var app=getApp();
var t = app;
const infoconfig= require('../../utils/als_config');
var Poster =require('../../poster.js');

Page({
    data: {
       TabCur: 0,
        tabNav: [ "热门", "最新"],
        votes: [],
        votes_new: [],
        votes_name:[],
        currentPage: 1,
        currentPage_new: 1,
        hidden: !1,
        checkID: "",
        pullDownRefreshState: !1,
        content_height: "",
        nodata: !1,
        toView: "",
        toView2: "",
        hasmore:true,
        type: 0,
        agreeNumber:"20%",
        disagreeNumber:"80%",
        userChoose:1,
        loading:true,
        answer:[],
        msgList:[],
        unitId:'',   
        canshow:true,
        default_img:'http://bmobfile.funnyfish.cn/2020/05/11/16555bbe40b88c158056807e57232761.png',
        posterConfig:{
        },
        answerImg:[],
        allImg:[],
    },
   
  
    tabSelect: function(t) {
        console.log(t);

        if(t.currentTarget.dataset.id==1&&this.data.votes_new.length==0){
            this.setData({
                TabCur: t.currentTarget.dataset.id,
                scrollLeft: 60 * (t.currentTarget.dataset.id - 1),
                hidden: !1,
                type: 0 == t.currentTarget.dataset.id ? "0" : 1
            });
            this.allRequest(1,1)
        }else{
            this.setData({
                TabCur: t.currentTarget.dataset.id,
                type: 0 == t.currentTarget.dataset.id ? "0" : 1,
                scrollLeft: 60 * (t.currentTarget.dataset.id - 1),

            });
        }
        // this.getVotes()
      
    },
  
    onCreatePoster(e) {
        let title=e.currentTarget.dataset.title;
        var b1=e.currentTarget.dataset.b1;
        var b2=e.currentTarget.dataset.b2;
        if(b1&&b2&&title){
        var fontSize=42;
        var textinfo="right";
        var bx=100;
        if(b1.length>8||b2.length>8){
            fontSize=30;
            textinfo="center";
            bx=40;
            console.log('b111==')
            if(b2.length>15){
                b2=b2.substring(0,15)+'...'
            }
            if(b1.length>12){
                bx=10;
            }
            if(b1.length>15){
                fontSize=28;
                b1=b1.substring(0,15)+'...'
                var bx=110;
                textinfo="left"
                
            }
        }
        
     
        var e = {
            width: 750,
            height: 1014,
            backgroundColor: "#fff",
            debug: !1,
            renderType: "timeline",
            blocks: [ {
                x: bx,
                y: 320,
                width: 200,
                height: 154,
                borderRadius: 20,
                text: {
                    width: 200,
                    height: 154,
                    lineHeight: 50,
                    textAlign: textinfo,
                    color: "#000",
                    baseLine: "top",
                    fontSize: fontSize,
                    text: b1,
                    lineNum: 3,
                },
                zIndex: 2
            }, {
                x: 440,
                y: 320,
                width: 210,
                height: 154,
                text: {
                    width: 200,
                    height: 154,
                    lineHeight: 50,
                    textAlign: "left",
                    color: "#000",
                    baseLine: "top",
                    fontSize: fontSize,
                    lineNum: 3,
                    text: b2
                },
                zIndex: 2
            } ],
            texts: [ {
                x: 100,
                y: 160,
                width: 550,
                lineHeight: 70,
                text:title,
                textAlign: "center",
                fontSize: 48,
                lineNum: 3,
                color: "#000000",
                baseLine: "middle",
                zIndex: 3
            }, {
                x: 100,
                y: 60,
                width: 550,
                height: 50,
                lineHeight: 50,
                textAlign: "center",
                fontSize: 30,
                text:"话题投票",
                color: "#8d76ff",
                zIndex: 3
            }, {
                x: 279,
                y: 860,
                width: 192,
                height: 20,
                lineHeight: 24,
                textAlign: "center",
                fontSize: 24,
                text: "识别二维码参与",
                color: "#000000",
                zIndex: 3
            } ],
            images: [ {
                width: 750,
                height: 1014,
                x: 0,
                y: 0,
                url: "/img/poster-bg2.jpg",
                zIndex: 1
            }, {
                width: 60,
                height: 60,
                x: 335,
                y: 390,
                url: "/img/VS.png",
                zIndex: 3
            }, {
                width: 192,
                height: 192,
                x: 279,
                y: 630,
                url: "/img/qrcode.jpeg",
                zIndex: 3
            } ]
        };
     
          Poster.default.create(e);
        }else{
            wx.showToast({
              title: '生成失败',
              icon:'none'
            })
        }
      },
    onPosterSuccess: function(t) {
        var e = t.detail;
        if(!e){return}
        wx.previewImage({
            current: e,
            urls: [ e ]
        });
    },
    showImg(t){
        var e = t.currentTarget.dataset.url;
       
        if(!e){return}
        wx.previewImage({
            current: e,
            urls: [ e ]
        });
    },
    onPosterFail: function(t) {
        console.error(t);
    },





    bindChange: function(t) {
        console.log("changeTbab")
        this.setData({
            TabCur: t.detail.current,
            type: 0 == t.detail.current ? "0" : 1
        });
        if(t.detail.current&&this.data.votes_new.length==0){
            this.allRequest(1,1)
        }
        
    },
    onShareAppMessage: function(t) {
        var e = wx.getStorageSync("uid"), a = t.target.dataset.voteid, o = wx.getStorageSync("nickName") || "朋友";
        return "button" === t.from && console.log(t), {
            title: o + "邀你投一票！",
            path: "/pages/vote_detail/vote_detail?shareFrom=share&uid=" + e + "&tid=" + a,
            success: function(t) {}
        };
    },
  
   onLoad: function() {
        var t = this;
    
        wx.getSystemInfo({
            success: function(e) {
                t.setData({
                    content_height: e.windowHeight
                });
            }
        });
        var names=wx.getStorageSync('votes_name');
        this.setData({
            votes_name:names,
            currentPage_new: 1,
            currentPage: 1
        })
    this.get_notic();
       
  
    this.allRequest(1,0);

    },
    onShow(){
        var msg=app.config.qqad
         if(msg){
            this.setData({
         
            unitId:msg
        })
         }
    },

    getAllimg(){
        var that=this
        var limit=0;
        var rand=(Math.random()+1)*10+30;
        limit=parseInt(limit+rand);
        var attr = {
            'limit': limit,
            'select':"uimg",
            'order':'-updatedAt',
          }

          return new Promise(function(resolve,reject){
        wx.Als.bmobFunc('vote_uimg', 'all', '',attr).then(res => {
            
            if (res.length > 0) {
              that.setData({
                allImg:res
      
              })
              resolve(res)
            }else if(res){
                resolve([])
            }else{
                reject('空头像')
            }
          })

        })
    },
   
    getInfo(a=10){
        let that=this
        let len=this.data.votes.length||a;
        let arr=[];
        for(var i=0;i<len;i++){
            arr[i]= that.getname();
        }
      
        return arr; 
    },
    getname(){

        var t = infoconfig.firstName.length, n = infoconfig.lastName.length;
        return infoconfig.firstName[this.GetRandomNum(0, t - 1)] + infoconfig.lastName[this.GetRandomNum(0, n - 1)];
    },
    GetRandomNum(e,t){
        var n = t - e, r = Math.random();
        return e + Math.round(r * n);
    },
    getNewList(skip=1,type=0){
            var that=this;
            var v = 100;
          var max = app.config.listnum ? app.config.listnum : (Math.random() + 0.1) * 10 * (1 + Math.random());
     
          var randnum = Math.floor(Math.random() * max) + 1;
          var limits = app.config.limit?app.config.limit:30;
         
            if(type==1){
                var param={
                  
                    'notlike':{
                        k:'show',
                        v:true
                    },
                    notlike2:{
                        k:'hot',
                        v:1

                    }
                    
                }
                var attr = {
                    'limit': limits,
                    'order':'-updatedAt',
                    skip:skip-1
          
                  }
            }else{
            var param = {
                like:{
                k:'hot',
                v:1
                },
               'notlike':{
                   k:'show',
                   v:true
               }
                
            };

            var attr = {
                'limit': limits,
                'order':'-updatedAt',
                skip:skip-1
      
              }
        }
    return new Promise(function(resolve, reject) {
            wx.Als.bmobFunc("vote_list", 'all',param, attr).then(res => {
            
              if (res.length > 0) {

                var names=wx.getStorageSync('votes_name');
                if(names.length<1200){
                let votes_name=that.getInfo(res.length);
                if(!(names instanceof Array)){
                    names=[];
                }
                var newnames=[];
                if(names){
                    newnames=names.concat(votes_name)
                }else{
                    newnames=names
                } 
                wx.setStorageSync('votes_name', newnames)
                that.setData({     
                    votes_name:newnames,
                })
            }
      
               resolve(res)
                
              }else{
                  wx.showToast({
                    title: '没有更多~',
                    icon:'none'
                  })
                  if(that.data.type==0){
                      that.setData({
                        hasmore:false
                      })
                  }
                 reject("vote_list_is error")
              }
            
          
            })
        })
         
           
          
    },
    get_notic() {
        let param = {
          'showQQ': true
        }
        wx.Als.bmobFunc('vote_gonggao', 'all', param).then(res => {
    
          if (res.length > 0) {
            this.setData({
              msgList: res,
    
            })
          }
        })
      },
    getList: function(skip=1) {
        var that=this;
        var v = 100;
      var max = app.config.listnum ? app.config.listnum : (Math.random() + 0.1) * 10 * (1 + Math.random());
      console.log(max)
      var randnum = Math.floor(Math.random() * max) + 1;
      console.log(app.config.randnum)
        console.log('randnum',randnum)
     
      
      var limits = app.config.limit?app.config.limit:10;
      
       
        var attr = {
          'limit': 3,
          'order':'-updatedAt',
          skip:skip

        }
        var param = {
            like:{
            k:'hot',
            v:1
            },
           'notlike':{
               k:'show',
               v:true
           }
            
        };
        
        wx.Als.bmobFunc("vote_list", 'all',param, attr).then(res => {
          console.log(res);
            wx.hideLoading()
          if (res.length > 0) {
            let votes_name=that.getInfo(res.length);
            var names=wx.getStorageSync('votes_name');
          
            if(!(names instanceof Array)){
                names=[];
            }
            var newnames=[];
            if(names){
                newnames=names.concat(votes_name)
            }else{
                newnames=names
            }
              
            wx.setStorageSync('votes_name', newnames)
            that.setData({
                
                votes_name:newnames,
                
            })
            that.setData({
                votes:res
            })
          
           
          }
          that.setData({
            hidden: !0
        })
      
        })
     
       
      
    },
  
    agree: function(t) {
        var e = t.currentTarget.dataset.id, a = this;
        let info=t.currentTarget.dataset.info;
        let type=t.currentTarget.dataset.type;
        let index=t.currentTarget.dataset.index;
        let answerImg=t.currentTarget.dataset.uimg;
        if(info){
            info=Number(info)
        }
     
        var uid=wx.getStorageSync('uid');
            console.log(info);
          
        if(!e||!uid||this.data.canshow==false){return}
        wx.showToast({
          title: '提交中...',
          icon:'none'
        })
        let param={
            uid:uid,
            vid:e
        }
        let attr={
            limit:1
        }
        this.setData({
            canshow:false
        })
        wx.Als.bmobFunc('vote_answer','all',param,attr).then(res=>{
           
            if(res&&res.length==0){
                a.add_vote(uid,e,info,index,type,answerImg);
                 app.addVoteNum(uid)

               
            }else{
                wx.showToast({
                  title: '已经回答',
                  icon:'none'
                })
            }

        })
        setTimeout(function(res){
            a.setData({
              canshow:true
            })
          },1000);
    },
    update_list(aid,vid,content=1){
let query = wx.Bmob.Query('vote_list');
const pointer = wx.Bmob.Pointer('vote_answer')
const relID = pointer.set(aid)
content=Number(content)

query.get(vid).then(res => {
  console.log(res)
  console.log("udpate")
  let c='vote_content'+content;
  let num1=Number(res[c])+1;
  console.log(num1);
  console.log("====")
  let num2=Number(res.group_count)+1;
 res.set('vote_content'+content,num1);
 res.set('group_count',num2);
 res.set('newid',relID); 
   res.save();

}).catch(err => {
  console.log(err)
})
    },
    add_vote(uid,vid,content1='',index=0,type=1,myArr=[]){
        let a=this;
        let content=Number(content1)
  
        const pointer = wx.Bmob.Pointer('vote_user')
        const poiID = pointer.set(uid)
        let param={
            uid:uid,
            vid:vid,
            content:content,
             userinfo:poiID
        }
        wx.Als.bmobFunc('vote_answer', 'add', param).then(res => {
            var uimg=wx.getStorageSync('uimg')
            var answerImg=myArr.length>0?myArr:a.getRandomArrayElements(a.data.allImg,6)
           
                if(uimg){
                    if(content==1){
                        answerImg.splice(2,1,{uimg:uimg})
                }else{
                    answerImg.splice(5,1,{uimg:uimg})
                }

            }
            if(type==2){
                var votes_new=a.data.votes_new
                var votearr='votes_new['+index+'].answer';
                var vote='votes_new['+index+']';
                var voteinfo=votes_new[index];
                var myanswer='votes_new['+index+'].answerImg';
             
                
            }else{
                var votes=a.data.votes
                var votearr='votes['+index+'].answer';
                var vote='votes['+index+']';
                var voteinfo=votes[index]
                var myanswer='votes['+index+'].answerImg';
            }
            
            voteinfo.group_count=voteinfo.group_count+1;
            var  contentinfo='vote_content'+content;
            voteinfo[contentinfo]= voteinfo[contentinfo]+1;
           
         
            let uid=wx.getStorageSync('uid')
            if(res){
                a.setData({
                    [votearr]:{content:content,uid:uid},
                    [vote]:voteinfo,
                    [myanswer]:answerImg
                })
                a.update_list(res.objectId,vid,content);
            }
           
          })
    },

    add_list(title,content1,content2,vote_content1=0,vote_content2=0,avatar=''){
        let that=this;
        if(!title||!vote_content2)return;
        var nick_name=wx.getStorageSync('nickName');
   
        var uid=wx.getStorageSync('uid');
        var group_count=Number(vote_content1)+Number(vote_content2)
        let param2={
            title:title
        }
        wx.showLoading({
            title: '添加中...',
          })
          let param={
            uid:uid,
            title:title,
            content1:content1,
            content2:content2,
            group_count:group_count,
            vote_content1:vote_content1,
            vote_content2:vote_content2,
    
            nick_name:nick_name,
            avatar:avatar,
            
          }
        wx.Als.bmobFunc('vote_list','all',param2).then(res=>{
            if(res.length>0){
                return;
            }else{
                wx.Als.bmobFunc('vote_list', 'add', param).then(res => {
                    console.log(res)
                    console.log(res)
                    wx.hideLoading();
                    if(res){
                    
                      wx.showToast({
                        title: '添加成功~',
                      })
              
                    }
                  })
            }
        })
    
      
      
     },
    onVote2: function(t) {
        var e = t.currentTarget.id.split("-"), a = this, o = wx.getStorageSync("FTE_ID"), n = "";
        "" != o && (n = "FTE_ID=" + o), wx.showLoading({
            title: "投票中..."
        }), wx.request({
            url: getApp().globalData.api_url + "/zxf/appclient/attitude_xz.php?act=vote",
            header: {
                "content-type": "application/x-www-form-urlencoded",
                cookie: n
            },
            method: "POST",
            data: {
                topic_id: e[0],
                vote_content: e[1]
            },
            success: function(t) {
                if (wx.hideLoading(), 0 == t.data.result) {
                    if (1 == a.data.type) o = a.data.votes; else var o = a.data.votes_new;
                    for (var n = 0; n < o.length; n++) for (var s = 0; s < o[n].group_by.length; s++) o[n].id == e[0] && (o[n].is_vote = 1, 
                    o[n].vote_content = e[1], o[n].group_by[s].vote_content == e[1] ? o[n].group_by[s].prec = a.Percentage(parseInt(o[n].group_by[s].count) + 1, parseInt(o[n].group_count) + 1) : o[n].group_by[s].prec = a.Percentage(parseInt(o[n].group_by[s].count), parseInt(o[n].group_count) + 1));
                    1 == a.data.type ? a.setData({
                        checkID: e[0],
                        votes: o
                    }) : a.setData({
                        checkID: e[0],
                        votes_new: o
                    });
                } else 1009 == t.data.result ? (wx.setStorageSync("avatarUrl", ""), wx.setStorageSync("nickName", ""), 
                wx.showToast({
                    title: t.data.msg,
                    icon: "none",
                    duration: 1e3,
                    mask: !0
                }), setTimeout(function() {
                    getApp().globalData.from_vote = 1, wx.navigateTo({
                        url: "/pages/login/index"
                    });
                }, 700)) : wx.showToast({
                    title: t.data.msg,
                    icon: "none",
                    duration: 1e3,
                    mask: !0
                });
            },
            fail: function() {
                wx.hideLoading(), wx.showToast({
                    title: "投票失败，请稍后再试",
                    icon: "none",
                    duration: 1500,
                    mask: !0
                });
            }
        });
    },
    onPullDownRefresh: function() {
        // console.log(3213), console.log("下拉刷新"), wx.setStorageSync("vote_ids", []);
        // var t = this;
        // 1 == t.data.type ? t.setData({
        //     pullDownRefreshState: !0,
        //     currentPage: 1
        // }) : t.setData({
        //     pullDownRefreshState: !0,
        //     currentPage_new: 1
        // }), wx.showLoading({
        //     title: "加载中..."
        // });
        // t.getVotes()
        if(this.data.type==1){
            this.setData({
                votes_new:[],
                currentPage_new:1
            })
            this.allRequest(1,1)
            setTimeout(() => {
                wx.stopPullDownRefresh();
            }, 1000);
        }else{
            wx.stopPullDownRefresh();
        }
    },
    getRandomArrayElements(arr, count) {
        var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
        while (i-- > min) {
            index = Math.floor((i + 1) * Math.random());
            temp = shuffled[index];
            shuffled[index] = shuffled[i];
            shuffled[i] = temp;
        }
        return shuffled.slice(min);
    },
    
  
    allRequest(skip=1){
        let that=this;
        let type=this.data.type;
var promise1 = this.getNewList(skip,type);



var promise2 =this.getAnswer();
var promise3=this.getAllimg();
        Promise.all([promise1, promise2,promise3]).then(function(values) {   
           
            if(values.length>=1){
             
                values[0].forEach(item => {
                    if(values[1]!=undefined){
                    values[1].forEach(ele=>{
                        if(item.objectId==ele.vid){
                            item.answer=ele
                        }
                     
            item.answerImg= that.getRandomArrayElements(values[2],6)
                    })
                }
                });
               
                if(type==1){
                   
                    let votes_new=that.data.votes_new
                    that.setData({
                        votes_new:votes_new.concat(values[0]),
                        hidden:!0
                    })
                }else{
                    let votes=that.data.votes
              
                    that.setData({
                        votes:votes.concat(values[0]),
                        hidden:!0
                    })
                }
              
                wx.hideLoading();
            }
          

          });
    },
    loadMore(){
         

            var t = this;
            wx.setStorageSync("vote_ids", []);
            let type=this.data.type
            if(type==0){
                if(t.data.hasmore==false){
                    return;
                }
            }
            var e = t.data.currentPage;
          
          
            if(type){
                e = t.data.currentPage_new;
            e++, t.setData({
                currentPage_new: e,
    
            })
            }else{
                e++;
                this.setData({
                    currentPage: e,
    
                })
            }
         
            this.setData({
                pullDownRefreshState: !1
            }), wx.showLoading({
                title: "加载中..."
            })
            // this.getList(e)
            this.allRequest(e)
    },
    getAnswer(){
        let that=this
        let uid=wx.getStorageSync('uid')
        if(!uid){return}
        let param={
            uid:uid
        }
        let attr={
            limit:490,
            order:'-updatedAt'
        }
       return new Promise(function(resolve,reject){
        wx.Als.bmobFunc("vote_answer", 'all',param,attr).then(res => {
            if(res){
                resolve(res)
            }else{
                resolve([])
                
            }

        })
       }).catch(res=>{
           console.log('oooo')
           reject('vote_answer_is error')
       })

    },
    onReachBottom: function() {
        // var t = this;
        // wx.setStorageSync("vote_ids", []);
        // let type=this.data.type
        // var e = t.data.currentPage;
        // console.error("onbottom!!")
      
        // if(type){
        //     e = t.data.currentPage_new;
        // e++, t.setData({
        //     currentPage_new: e,

        // })
        // }else{
        //     e++;
        //     this.setData({
        //         currentPage: e,

        //     })
        // }
     
        // this.setData({
        //     pullDownRefreshState: !1
        // }), wx.showLoading({
        //     title: "加载中..."
        // })
        // // this.getList(e)
        // this.allRequest(e)
    },
    getVotes: function() {
        var t = this, e = wx.getStorageSync("FTE_ID"), a = "";
        "" != e && (a = "FTE_ID=" + e);
        var o = 1 == t.data.type ? t.data.currentPage : t.data.currentPage_new;
        wx.request({
            url: getApp().globalData.api_url + "/zxf/appclient/social/v5/attitude.php?act = list",
            header: {
                "content-type": "application/x-www-form-urlencoded",
                cookie: a
            },
            method: "POST",
            data: {
                page:13,
                type: 1,
                size:10,
                pagesize:10,
                limit:10

            },
            success: function(e) {
                t.setData({
                    hidden: !0
                }), 0 == e.data.result && (0 == e.data.data.list.length && t.setData({
                    nodata: !0
                }), 0 === e.data.data.list.length && o > 1 && wx.showToast({
                    title: "全部数据已加载，已无更多内容",
                    icon: "none",
                    duration: 1500,
                    mask: !0
                }), t.data.pullDownRefreshState ? (wx.hideLoading(), 1 == t.data.type ?(t.setData({
                    votes: e.data.data.list,
                    pullDownRefreshState: !1
                })
              

                
                ) : t.setData({
                    votes_new: e.data.data.list,
                    pullDownRefreshState: !1
                })) : (console.log("上拉加载"), wx.hideLoading(), 1 == t.data.type ? t.setData({
                    votes: t.data.votes.concat(e.data.data.list)
                }) : t.setData({
                    votes_new: t.data.votes_new.concat(e.data.data.list)
                })
                
                )
                );
            },
            fail: function() {
                wx.showToast({
                    title: "网络异常，请稍后再试",
                    icon: "none",
                    duration: 1500,
                    mask: !0
                });
            }
        });
    },
    showDetail(info){
        let that=this
      
        let votes=this.data.votes
        console.log(votes)
        for(var i=0;i<votes.length;i++){
            if(votes[i].content3==''&&votes[i].content1.indexOf("http")==-1){
                console.log('res===',i);
                console.log(votes[i])
                let title=votes[i].title;
                let content1=votes[i].content1
                let content2=votes[i].content2
                let vote_content1=votes[i].group_by[0].count
                let vote_content2=votes[i].group_by[1].count
                let avatar=votes[i].avatar;
                console.log(vote_content1,vote_content2)
                console.log(title)
                that.add_list(title,content1,content2,Number(vote_content1),Number(vote_content2),avatar)
            }
        }
    },
    targetToVoteDetail: function(t) {
        var e = t.currentTarget.dataset.voteid;
        if(!e){return}
        wx.navigateTo({
            url: "/pages/vote_detail/vote_detail?tid=" + e,
            success: function(t) {
                console.log(t);
            }
        });
    },
    Percentage: function(t, e) {
        return 0 == e ? 0 : (Math.round(t / e * 1e4) / 100).toFixed(0);
    },



});



